<?php defined('SYSPATH') OR die('No direct access allowed.');

class Default_Controller extends Controller
{
	/**
	 * 首页(index)
	 */
	/*{{{*/
    public function index($offset=0)
    {
		$this->_cookieLogin();
        //每页显示10个
		$itemsPerPage = 10;

        $view = new View('index');
        $view->currentHl = '';
        $article = ORM::factory('article');
		//总条数
		$db = new Database();
		$num = $db->count_records('articles');

		$offset = $this->_getOffset($offset,$itemsPerPage,$num);
        $view->articles = $article->orderby('id','DESC')->find_all($itemsPerPage,$offset);

		//我发布的信息和我的收集
        $mypub = $this->_myPub();
        $mycollect = $this->_myCollect();
        $view->collects = $mycollect;
        $view->pubs = $mypub;

		//上一页，下一页
		$next = $this->_getPageLink('index','next',$offset,$itemsPerPage,$num);
		$prev = $this->_getPageLink('index','prev',$offset,$itemsPerPage,$num);

		$view->nextPage = $next;
		$view->prevPage = $prev;
        $view->render(true);
	}
	/*}}}*/

	/**
	 * 查看某一用户发表的信息(viewuser)
	 */
	/*{{{*/
	public function viewuser($user_id,$offset=0)
	{
		//每页显示10个
		$itemsPerPage = 10;
		$user_id = (int)$user_id;
        $view = new View('index');
        $view->currentHl = '';
        $article = ORM::factory('article');
		//总条数
		$db = new Database();
		$num = $db->where('user_id',$user_id)->count_records('articles');

		$offset = $this->_getOffset((int)$offset,$itemsPerPage,$num);
        $view->articles = $article->where('user_id',$user_id)->orderby('id','DESC')->find_all($itemsPerPage,$offset);

		//我发布的信息和我的收集
        $mypub = $this->_myPub();
        $mycollect = $this->_myCollect();
        $view->collects = $mycollect;
        $view->pubs = $mypub;

		//上一页，下一页
		$next = $this->_getPageLink('viewuser','next',$offset,$itemsPerPage,$num,$user_id);
		$prev = $this->_getPageLink('viewuser','prev',$offset,$itemsPerPage,$num,$user_id);

		$view->nextPage = $next;
		$view->prevPage = $prev;
        $view->render(true);
	}
	/*}}}*/

    /**
     * 我的收藏列表(mycollect)
	 */
	/*{{{*/
    public function mycollect($offset=0)
    {
		if(!$this->_isLogin())
		{
			$this->_popAlert('你尚未登录或已超时');
		}
		$itemsPerPage = 10;
        $view = new View('index');

        $mypub = $this->_myPub();
        $mycollect = $this->_myCollect();
        $view->collects = $mycollect;
        $view->pubs = $mypub;

		//总条数
		$db = new Database();
		$view->articles = array();
		if(count($mycollect)>0)
			$num = $db->in('id',$mycollect)->count_records('articles');
		else
			$num = 0;

        $article = ORM::factory('article');
		$offset = $this->_getOffset($offset,$itemsPerPage,$num);

        if(count($mycollect)>0)
        $view->articles = $article->in('id',$mycollect)->orderby('id','DESC')->find_all($itemsPerPage,$offset);
        $view->currentHl = 'collect';//高亮收藏按钮

		//上一页，下一页
		$next = $this->_getPageLink('mycollect','next',$offset,$itemsPerPage,$num);
		$prev = $this->_getPageLink('mycollect','prev',$offset,$itemsPerPage,$num);

		$view->nextPage = $next;
		$view->prevPage = $prev;

        $view->render(true);
    }
	/*}}}*/

    /**
     * 我发布过的信息(mypub)
     */
	/*{{{*/
    public function mypub($offset=0)
    {
		if(!$this->_isLogin())
		{
			$this->_popAlert('你尚未登录或已超时');
		}
		$itemsPerPage = 10;
        $view = new View('index');

        $mypub = $this->_myPub();
        $mycollect = $this->_myCollect();
        $view->collects = $mycollect;
        $view->pubs = $mypub;

		//总条数
		$db = new Database();
		if(count($mypub)>0)
			$num = $db->in('id',$mypub)->count_records('articles');
		else
			$num = 0;

		$offset = $this->_getOffset($offset,$itemsPerPage,$num);

        $article = ORM::factory('article');
		$view->articles = array();
        if(count($mypub)>0)
        $view->articles = $article->in('id',$mypub)->orderby('id','DESC')->find_all($itemsPerPage,$offset);
        $view->currentHl = 'pub';//高亮收藏按钮

		//上一页，下一页
		$next = $this->_getPageLink('mypub','next',$offset,$itemsPerPage,$num);
		$prev = $this->_getPageLink('mypub','prev',$offset,$itemsPerPage,$num);

		$view->nextPage = $next;
		$view->prevPage = $prev;

        $view->render(true);
    }
	/*}}}*/

	/**
	 * 查看回复(viewcmt)
	 */
	/*{{{*/
	public function viewcmt($art_id)
	{
		//echo $art_id;
		$cmts = ORM::factory('comment')->where('article_id',(int)$art_id)->find_all();
		$cmtArr = array();
		foreach($cmts as $cmt)
		{
			$arr = array();
			$arr['pubdate'] = date("y/m/d H:i",$cmt->pubdate);
			$arr['content'] = $cmt->content;
			$arr['user_id'] = $cmt->user_id;
			$arr['avatar'] = $cmt->user->avatar;
			$arr['username'] = $cmt->user->username;
			$cmtArr[] = $arr;
		}
		echo json_encode($cmtArr);
	}
	/*}}}*/ 

	/**
	 * 添加回复(addcmt)
	 */
	/*{{{*/
	public function addcmt($art_id)
	{
		$post = $this->input->post();
		if(trim($post['content'])=='')
		{
			//$this->_popAlert('留言内容不能为空');
			echo '-2';//留言不能为空
			exit;
		}
		if($user_id = $this->_isLogin())
		{
			$cmt = ORM::factory('comment');
			$cmt->article_id = (int)$art_id;
			$cmt->user_id = $user_id;
			$cmt->pubdate = time();
			$cmt->content = mysql_real_escape_string(preg_replace("/\n/","<br>",$post['content']));
			$cmt->save();
			//$this->_popAlert('留言添加成功');
			$user = ORM::factory('user',$user_id);//这里其实多了一次查询
			$avatar = $user->avatar;
			$jsonArr = array();
			$jsonArr['art_id'] = (int)$art_id;
			$jsonArr['avatar'] = $avatar;
			$jsonArr['user_id'] = $user_id;
			$jsonArr['pubdate'] = date('y/m/d H:i',time());
			$jsonArr['content'] = mysql_real_escape_string(preg_replace("/\n/","<br>",$post['content']));
			echo json_encode($jsonArr);
			exit;
		}
		else
		{
			//$this->_popAlert('你尚未登陆或已超时');
			echo '-1';//尚未登录或已超时
			exit;
		}
	}
	/*}}}*/ 

    /*
     * 用户注册(reg)
     */
	/*{{{*/
    public function reg()
    {
        $post = new Validation($this->input->post());
        $post->pre_filter('trim');
        $post->add_rules('username','required');
        $post->add_rules('password','required');
        $post->add_rules('password_again','required');
        $post->add_rules('password','matches[password_again]');
        if($post->validate())
        {
			if(!$this->_checkUsername($this->input->post('username')))
			{
				echo "-2";//用户名已被注册
				exit;
			}
            //添加到数据库
            $user = ORM::factory('user');
            $user->username = $this->input->post('username');
            $user->password = md5($this->input->post('password'));
            $user->regdate = time();
            $user->save();
            $session = Session::instance();
            $session->set('user_id',$user->id);
            setcookie('username',$this->input->post('username'),time()+(3600*30),'/');
            setcookie('password',md5($this->input->post('password')),time()+(3600*30),'/');
            echo '1';
            exit;
        }
        else
        {
            $errors = $post->errors();
            echo json_encode($errors);
            exit;
        }
    }
	/*}}}*/

	/**
	 * 编辑信息，如上传头像，修改密码(editinfo)
	 */
	/*{{{*/
	public function editinfo()
	{
		$session = Session::instance();
		$user_id = $session->get('user_id');
		if($user_id=='' || $user_id=='undefined')
		{
			$this->_popAlert('你尚未登陆或已超时');
		}
		$user = ORM::factory('user',$user_id);

		$filename = '';
		//验证头像上传
		if($_FILES['avatar']['name']!='')
		{
			$_FILES = Validation::factory($_FILES)->add_rules('avatar','upload::type[gif,jpg,jpeg,png]','upload::size[1M]');
			if($_FILES->validate())
			{
				$filepath = Kohana::config('upload.directory');
				$rnd = rand(10000, 100000);
				$filename = $rnd.time().".jpg";
				$file = upload::save('avatar');
				Image::factory($file)->resize(48,48,Image::NONE)
				->save($filepath.'/avatar/'.$filename);
				unlink($file);
				$user->avatar = $filename;
			}
		}
		$post = $this->input->post();
		if($post['oldpwd']!='')
		{
			if($post['newpwd']=='' || $post['newpwdagain']=='')
			{
				$this->_popAlert('新密码不能为空');
			}
			if($post['newpwd']!=$post['newpwdagain'])
			{
				$this->_popAlert('两次密码不符');
			}
			if(md5($post['oldpwd'])!=$user->password)
			{
				$this->_popAlert('原密码不正确');
			}
			$user->password = md5($post['newpwd']);
			setcookie('password',md5($post['newpwd']),time()+(3600*30),'/');
		}
		$user->save();
		$this->_popAlert('信息修改成功');
	}
	/*}}}*/ 

    /*
     * 退出(logout)
     */
	/*{{{*/
    public function logout()
    {
        $session = Session::instance();
        $session->destroy();
        setcookie('username', '', 0,'/');
        setcookie('password', '', 0,'/');
        url::redirect(url::site('default'));
    }
	/*}}}*/

    /*
     * 用户登录(login)
     */
	/*{{{*/
    public function login()
    {
        if($this->input->post('username')!='' && $this->input->post('password')!='')
        {
            $rs = ORM::factory('user')->where('username',$this->input->post('username'))->find();
            if($rs->password != 'undefind' && $rs->password != '')
            {
                if($rs->password == md5($this->input->post('password')))
                {
                    //登录成功
                    $session = Session::instance();
                    $session->set('user_id',$rs->id);
                    setcookie('username',$this->input->post('username'),time()+(3600*30),'/');
                    setcookie('password',md5($this->input->post('password')),time()+(3600*30),'/');
                    echo '1';
                    exit;
                }
                else
                {
                    echo '0';
                    exit;
                }
            }
            else
            {
                echo '0';
                exit;
            }
        }
        else
        {
            echo '0';
            exit;
        }
    }
	/*}}}*/

	/**
	 * 私有方法，Cookie自动登录(_cookieLogin)
	 */
	/*{{{*/
	private function _cookieLogin()
	{
		if(isset($_COOKIE['username']) && $_COOKIE['username']!='' && $_COOKIE['username']!='undefind')
		{
			$cookieUsername = $_COOKIE['username'];
			$user = ORM::factory('user')->where('username',$cookieUsername)->find();
			if($_COOKIE['password'] == $user->password)
			{
				$session = Session::instance();
				$session->set('user_id',$user->id);
			}
		}	
	}
	/*}}}*/

    /**
     * 删除信息(delinfo)
     */
	/*{{{*/
    public function delinfo()
    {
        $post = $this->input->post();
        $art_id = (int)$post['article_id'];
        //判断用户
        $article = ORM::factory('article',$art_id);
        $real_user_id = $article->user->id;
        $session = Session::instance();
        if($session->get('user_id')!=$real_user_id)
        {
            //不是该信息的用户，无权删除
            echo '-1';
            exit;
        }
        else
        {
            //删除收藏关联
            $db = new Database();
            $db->query('delete from articles_users where article_id="'.$art_id.'"');
			//删除回复
			$db->query('delete from comments where article_id="'.$art_id.'"');
            if($article->delete())
            {
                //删除成功
                echo '1';
                exit;
            }
            else
            {
                //删除失败
                echo '0';
                exit;
            }

        }
    }
	/*}}}*/

    /**
     * 发布文本内容,type=1(pubtxt)
     * 必填的都是content，可选的都是intro
     */
	/*{{{*/
    public function pubtxt()
    {
        $this->_pubInfo(1, $this->input->post());
        
    }
	/*}}}*/

    /**
	 * 添加链接信息(publink)
	 */
	/*{{{*/
    public function publink()
    {
        $this->_pubInfo(2, $this->input->post());
    }
	/*}}}*/

	/**
     * 添加视频信息(pubvideo)
	 */
	/*{{{*/
    public function pubvideo()
    {
        $this->_pubInfo(3, $this->input->post());
    }
	/*}}}*/

	/**
	 * 添加图像信息(pubpic)
	 */
	/*{{{*/
	public function pubpic()
	{
        $this->_pubInfo(4, $this->input->post());
	}
	/*}}}*/


    /**
     * 加入收藏(addcollect)
     */
	/*{{{*/
    public function addcollect()
    {
        $art_id = (int)$this->input->post('art_id');
        if($user_id = $this->_isLogin())
        {
            $user = ORM::factory('user',$user_id);
            $user->add(ORM::factory('article',$art_id));
            if($user->save())
            {
                echo '1';//保存成功
                exit;
            }
            else
            {
                echo '0';//保存失败
                exit;
            }
        }
    }
	/*}}}*/

    /**
     * 取消收藏(removecollect)
     */
	/*{{{*/
    public function removecollect()
    {
        $art_id = (int)$this->input->post('art_id');
        if($user_id = $this->_isLogin())
        {
            $user = ORM::factory('user',$user_id);
            //$user->articles = array($art_id);
            $user->remove(ORM::factory('article',$art_id));
            if($user->save())
            {
                echo '1';//保存成功
                exit;
            }
            else
            {
                echo '0';//保存失败
                exit;
            }
        }
    }
	/*}}}*/

	/**
	 * 私有方法，发布信息(_pubInfo)
	 */
	/*{{{*/
    private function _pubInfo($type,$post)
    {
		if($type!='4')//因为当发布的是图片信息时，content可能为空
		{
			$this->_checkLogin();
			$this->_checkContent($post);
		}

        if($post['article_id']=='')
        {
            $session = Session::instance();
            $user_id = $session->get('user_id');
            $article = ORM::factory('article');
            $article->user_id = $user_id;
            $article->pubdate = time();
            
        }
        else
        {
            $article = ORM::factory('article',(int)($post['article_id']));
        }
        $article->content = mysql_real_escape_string(preg_replace("/\n/","<br>",$post['content']));
        $article->intro = mysql_real_escape_string(preg_replace("/\n/","<br>",$post['intro']));

        switch($type)
        {
            case 1://文本信息
                $article->type = 1;
                $article->save();
                echo '1';
                break;
            case 2://链接信息
                if($post['linktitle']=='')
                {
                    echo '-2';//链接标题不能为空
                    exit;
                }
                else
                {
                    $article->type = 2;
                    $article->linktitle = mysql_real_escape_string($post['linktitle']);
                    $article->save();
                    echo '1';
                }
                break;
            case 3://视频信息
                $article->type = 3;
                $article->save();
                echo '1';
                break;
			case 4://图像信息，上传图片的优先级高于图像网址
				$session = Session::instance();
				if($session->get('user_id')=='' || $session->get('user_id')=='undefined')
				{
					$this->_popAlert('你尚未登录，请登陆后再执行此功能');
				}
				if($_FILES['pic']['name']!='')
				{
					$_FILES = Validation::factory($_FILES)->add_rules('pic','upload::type[gif,jpg,jpeg,png]','upload::size[2M]');
					if($_FILES->validate())
					{
						$uploadpath = Kohana::config('upload.directory');
						$rnd = rand(10000, 100000);
						//获取文件后缀名
						$fileArr = explode(".",$_FILES['pic']['name']);
						$ext = $fileArr[count($fileArr)-1];
						$filename = $rnd.time().'.'.$ext;

						$filepath = $this->_createMonthFolder();
						//注意，不能使用save()方法，会删除掉$_FILES['pic']['tmp_name']
						$imgSize = getimagesize($_FILES['pic']['tmp_name']);
						//如果宽度小于480的话不修改
						if($imgSize[0]>480)
						{
							$file = upload::save('pic');
							Image::factory($file)->resize(480,480,Image::WIDTH)->save($uploadpath.'/'.$filepath.$filename);
							unlink($file);
						}
						else
						{
							$path = $uploadpath.'/'.$filepath.$filename;
							move_uploaded_file($_FILES['pic']['tmp_name'],$path);
						}
						
						$article->content = $filepath.$filename;
					}
					else
					{
						$this->_popAlert('上传文件格式不符，或超过了2M');
					}
				}
				else
				{
					if($post['content']=='')
					{
						$this->_popAlert('图片网址不能为空');
					}
					if(!valid::url($post['content']))
					{
						$this0>_popAlert('图片网址有误');
					}
				}
				$article->type=4;
				$article->save();
				$this->_popAlert('图片信息上传成功');
				break;
			default:
				break;
        }
        exit;
    }
	/*}}}*/

    /**
     * 私有方法，检查是否已经登陆(_checkLogin)
     */
	/*{{{*/
    private function _checkLogin()
    {
        if(!$this->_isLogin())
        {
            echo '-1';
            exit;
        }
    }
	/*}}}*/

    /**
     * 私有方法，检查content是否为空(_checkContent)
     */
	/*{{{*/
    private function _checkContent($post)
    {
        //如果内容为空
        if(trim($post['content'])=='')
        {
            echo '0';
            exit;
        }
    }
	/*}}}*/

    /**
     * 私有方法，检查是否已经登陆(_isLogin)
     */
	/*{{{*/
    private function _isLogin()
    {
        $session = Session::instance();
        if(($session->get('user_id')=='') || ($session->get('user_id')=='undefined'))
        {
            return false;
        }
        else
        {
            return $session->get('user_id');
        }
    }
	/*}}}*/

	/**
	 * 私有方法，创建对应月份的文件夹(_createMonthFolder)
	 */
	/*{{{*/
   	private function _createMonthFolder()
	{
		//获取上传文件夹的位置
		$uploadDir = Kohana::config('upload.directory');
		$year = date("Y");
		if(!file_exists($uploadDir.'/'.$year))
		{
			mkdir($uploadDir.'/'.$year);
		}
		$month = date("m");
		$filePath = $uploadDir.'/'.$year.'/'.$month;
		if(!file_exists($filePath))
		{
			mkdir($filePath);
		}
		return $year.'/'.$month.'/';
	}	
	/*}}}*/

	/**
	 * 私有方法，弹出框(_popAlert)
	 */
	/*{{{*/
	private function _popAlert($msg)
	{
		$url = url::site();
		echo <<<EOT
		<script type="text/javascript">alert('$msg');location.href="$url"</script>
EOT;
		exit;
	}
	/*}}}*/

    /**
     * 私有方法，我发布过的信息(_myPub)
     */
	/*{{{*/
    private function _myPub()
    {
        $art_id = array();
        if($user_id = $this->_isLogin())
        {
            $user = ORM::factory('user',$user_id);
            $art_ids = array();
            foreach($user->articles as $article)//这样获取关联数据
            {
                $art_id[] = $article->id;
            }
        }
        return $art_id;
    }
	/*}}}*/

    /**
     * 私有方法，我所有的收藏(_myCollect)
     */
	/*{{{*/
    private function _myCollect()
    {
        $colls = array();//存放收藏的数组
        if($user_id = $this->_isLogin())
        {
            $db = new Database();
            $collects = $db->query('select article_id from articles_users where user_id="'.$user_id.'"')->as_array();
            foreach($collects as $collect)
            {
                $colls[]=($collect->article_id);
            }
        }
        return $colls;
	}
	/*}}}*/

	/**
	 * 私有方法，返回计算后的offset，用于分页(_getOffset)
	 */
	/*{{{*/
	private function _getOffset($offset,$itemsPerPage,$num)
	{
		if($offset>$num)//偏移量大于总数
		{
			$offset = floor($num/$itemsPerPage)*$itemsPerPage;
		}
		if($offset<=0)//第一页
		{
			$offset = 0;
		}
		return $offset;
	}
	/*}}}*/ 

	/**
	 * 私有方法，返回上一页，下一页的链接(_getPageLink)
	 */
	/*{{{*/
	private function _getPageLink($pageType,$prevOrNext,$offset,$itemsPerPage,$num,$user_id=1)
	{
		$hasNext = true;
		$hasPrev = true;
		if($offset<$num && ($offset+$itemsPerPage)>=$num)//没有下一页了
		{
			$hasNext = false;
		}
		if($offset>$num)//偏移量大于总数
		{
			$hasNext = false;
		}
		if($offset<=0)//第一页
		{
			$hasPrev = false;
		}
		if($prevOrNext == 'prev')
		{
			if($pageType == 'index')
				$prevLink = 'default/index/'.($offset-$itemsPerPage);
			else if($pageType == 'mycollect')
				$prevLink = 'default/mycollect/'.($offset-$itemsPerPage);
			else if($pageType == 'viewuser')
				$prevLink = 'default/viewuser/'.$user_id.'/'.($offset-$itemsPerPage);
			else
				$prevLink = 'default/mypub/'.($offset-$itemsPerPage);

			$prev = $hasPrev?'<a href="'.url::site($prevLink).'">上一页</a>':'上一页';
			return $prev;
		}
		else
		{
			if($pageType == 'index')
				$nextLink = 'default/index/'.($offset+$itemsPerPage);
			else if($pageType == 'mycollect')
				$nextLink = 'default/mycollect/'.($offset+$itemsPerPage);
			else if($pageType == 'viewuser')
				$nextLink = 'default/viewuser/'.$user_id.'/'.($offset+$itemsPerPage);
			else
				$nextLink = 'default/mypub/'.($offset+$itemsPerPage);
			$next = $hasNext?'<a href="'.url::site($nextLink).'">下一页</a>':'下一页';
			return $next;
		}
	}
	/*}}}*/ 

	/**
	 * 私有方法，判断用户名是否已被注册
	 */
	/*{{{*/
	private function _checkUsername($username)
	{
		$user = ORM::factory('user')->where('username',$username)->find();
		if($user->username=='')
		{
			return true;//用户名不存在，可以使用
		}
		else
		{
			return false;//用户名已被注册
		}
	}
	/*}}}*/
}
